package mail

import (
	"crypto/tls"
	"fmt"
	"github.com/Unknwon/goconfig"
	log "github.com/YoungPioneers/blog4go"
	"gopkg.in/gomail.v2"
	"strconv"
	"strings"
)

//发送邮件
func SendMail(subject string, message string, mail_to string, mail_from string, mail_user string,
	mail_pass string, mail_smtp string, mail_smtp_port string, mail_tls string) {
	mail_smtp_port_int, err := strconv.Atoi(mail_smtp_port)
	if err != nil {
		log.Error("mail_smtp_port转数字失败")
	}
	mail_to_s := strings.Split(mail_to, ";")
	m := gomail.NewMessage()
	m.SetHeader("From", mail_from)
	m.SetHeader("To", mail_to_s...)
	m.SetHeader("Subject", subject)
	m.SetBody("text/html", message)
	d := gomail.NewDialer(mail_smtp, mail_smtp_port_int, mail_user, mail_pass)
	if mail_tls == "false" {
		d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
	}
	if err := d.DialAndSend(m); err != nil {
		fmt.Println(err)
	}
	return
}

//获取邮件配置
func GetMailConfig(cfg *goconfig.ConfigFile) (string, string, string, string, string, string, string) {

	//获取邮件配置信息
	mail_to, err := cfg.GetValue("MAIL", "MAIL_TO")
	if err != nil {
		log.Error("读取邮件配置:MAIL_TO 的值出错")
	}

	mail_from, err := cfg.GetValue("MAIL", "MAIL_FROM")
	if err != nil {
		log.Error("读取邮件配置:MAIL_FROM 的值出错")
	}

	mail_user, err := cfg.GetValue("MAIL", "MAIL_USER")
	if err != nil {
		log.Error("读取邮件配置:MAIL_USER 的值出错")
	}

	mail_pass, err := cfg.GetValue("MAIL", "MAIL_PASS")
	if err != nil {
		log.Error("读取邮件配置:MAIL_PASS 的值出错")
	}

	mail_smtp, err := cfg.GetValue("MAIL", "MAIL_SMTP")
	if err != nil {
		log.Error("读取邮件配置:MAIL_SMTP 的值出错")
	}

	mail_smtp_port, err := cfg.GetValue("MAIL", "MAIL_SMTP_PORT")
	if err != nil {
		log.Error("读取邮件配置:MAIL_SMTP_PORT 的值出错")
	}

	mail_tls, err := cfg.GetValue("MAIL", "MAIL_TLS")
	if err != nil {
		log.Error("读取邮件配置:MAIL_TLS 的值出错")
	}

	return mail_to, mail_from, mail_user, mail_pass, mail_smtp, mail_smtp_port, mail_tls
}
